<template>
  <div class="warp">
    <div class="home-container">
      <div class="content-wrapper">
        <h2 class="page-title">Excel转换工具</h2>

        <!-- 文件上传区域 -->
        <el-upload class="upload-area" drag :accept="'.xlsx,.xls'" :auto-upload="false" :limit="1"
          :on-change="handleFileChange" :on-remove="handleRemove" :before-upload="beforeUpload">
          <el-icon class="upload-icon">
            <Upload />
          </el-icon>
          <div class="upload-text">
            <div>点击或拖拽上传Excel文件</div>
            <div class="upload-tip">支持 .xlsx, .xls 格式</div>
          </div>
        </el-upload>

        <!-- 范围参数表单 -->
        <el-card class="range-card">
          <div class="range-form">
            <div class="range-row">
              <div class="range-item">
                <span class="label">起始列：</span>
                <el-input-number v-model="startColumn" :min="0" controls-position="right" placeholder="起始列" />
              </div>
              <div class="range-item">
                <span class="label">末尾列：</span>
                <el-input-number v-model="endColumn" :min="0" controls-position="right" placeholder="末尾列" />
              </div>
            </div>

            <div class="range-row">
              <div class="range-item">
                <span class="label">起始行：</span>
                <el-input-number v-model="startRow" :min="0" controls-position="right" placeholder="起始行" />
              </div>
              <div class="range-item">
                <span class="label">末尾行：</span>
                <el-input-number v-model="endRow" :min="0" controls-position="right" placeholder="末尾行" />
              </div>
            </div>
          </div>
        </el-card>

        <!-- 转换按钮 -->
        <el-button type="success" :loading="isConverting" :disabled="!isRangeValid || !selectedFile"
          @click="handleUploadAndConvert" size="large" style="width: 200px;">
          {{ isConverting ? '转换中...' : '开始转换' }}
        </el-button>
      </div>

      <!-- 主题切换 -->
      <el-switch v-model="isDark" class="theme-switch" @change="toggleTheme" :active-icon="Moon"
        :inactive-icon="Sunny" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Moon, Sunny } from '@element-plus/icons-vue'
import { useDark, useToggle } from '@vueuse/core'
import request from '@/utils/request'

const isConverting = ref(false)
const isDark = useDark()
const toggleTheme = useToggle(isDark)
const selectedFile = ref(null)

// 范围参数
const startColumn = ref(0)
const endColumn = ref(0)
const startRow = ref(0)
const endRow = ref(0)

// 验证范围参数 - 只验证不为空且不小于0
const isRangeValid = computed(() => {
  return startColumn.value >= 0 &&
    endColumn.value >= 0 &&
    startRow.value >= 0 &&
    endRow.value >= 0
})

// 文件选择处理
const handleFileChange = (file) => {
  selectedFile.value = file
}

// 文件移除处理
const handleRemove = () => {
  selectedFile.value = null
}

// 上传前验证
const beforeUpload = (file) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  return true
}

// 上传并转换
const handleUploadAndConvert = async () => {
  if (!isRangeValid.value) {
    ElMessage.error('请填写正确的数据范围!')
    return
  }

  if (!selectedFile.value) {
    ElMessage.error('请选择文件!')
    return
  }

  isConverting.value = true
  ElMessage.info('正在转换，请稍候...')

  try {
    // 创建 FormData
    const formData = new FormData()
    formData.append('file', selectedFile.value.raw)
    formData.append('startColumn', startColumn.value)
    formData.append('endColumn', endColumn.value)
    formData.append('startRow', startRow.value)
    formData.append('endRow', endRow.value)

    const response = await request({
      url: '/convert',
      method: 'post',
      data: formData,
      responseType: 'blob',
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    // 创建下载
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'converted.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('转换成功')
    // 清除已选文件
    selectedFile.value = null
  } catch (error) {
    console.error('转换错误:', error)
    ElMessage.error('转换失败，请重试')
  } finally {
    isConverting.value = false
  }
}
</script>

<style lang="scss" scoped>
.warp {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.home-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  padding: 2rem;

  .content-wrapper {
    width: 100%;
    max-width: 600px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2rem;

    .page-title {
      margin: 0;
      color: var(--el-text-color-primary);
      font-size: 1.8rem;
      font-weight: 500;
    }

    .upload-area {
      width: 100%;

      :deep(.el-upload-dragger) {
        width: 100%;
      }

      .upload-icon {
        font-size: 48px;
        color: var(--el-color-primary);
        margin-bottom: 1rem;
      }

      .upload-text {
        text-align: center;

        .upload-tip {
          font-size: 0.9rem;
          color: var(--el-text-color-secondary);
          margin-top: 0.5rem;
        }
      }
    }

    .range-card {
      width: 100%;

      .range-form {
        display: flex;
        flex-direction: column;
        gap: 1.5rem;

        .range-row {
          display: flex;
          justify-content: space-between;
          gap: 2rem;

          .range-item {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 1rem;

            .label {
              white-space: nowrap;
              color: var(--el-text-color-regular);
            }

            .el-input-number {
              width: 120px;
            }
          }
        }
      }
    }

    .convert-btn {
      min-width: 200px;
    }
  }
}

.theme-switch {
  position: fixed;
  top: 20px;
  right: 20px;
}
</style>